package com.bstek.demo.service;

import com.bstek.urule.Utils;
import com.bstek.urule.action.WorkingMemoryHolder;
import com.bstek.urule.exception.RuleException;
import com.bstek.urule.model.GeneralEntity;
import com.bstek.urule.model.library.action.annotation.ActionBean;
import com.bstek.urule.model.library.action.annotation.ActionMethod;
import com.bstek.urule.model.library.action.annotation.ActionMethodParameter;
import com.bstek.urule.runtime.WorkingMemory;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 自定义内置动作：无需额外的配置直接能在设计器页面上显示
 */
@Component("myInnerAction")
@ActionBean(name = "自定义内置动作")
public class MyInnerAction {

    @ActionMethod(name = "去空格")
    @ActionMethodParameter(names = {"目标字符串"})
    public String trim(String str) {
        if (str == null) {
            return "";
        }
        return str.trim();
    }

    @ActionMethod(name = "截取字符串")
    @ActionMethodParameter(names = {"目标字符串", "开始位置", "结束位置"})
    public String substring(String str, int start, int end) {
        return str.substring(start, end);
    }

    @ActionMethod(name = "判断字符串是不是数字")
    @ActionMethodParameter(names = {"目标字符串"})
    public boolean isNumber(String str) {
        return NumberUtils.isNumber(str);
    }

    @ActionMethod(name = "字符串转换成数字")
    @ActionMethodParameter(names = {"目标字符串"})
    public double toNumber(String str) {
        if (NumberUtils.isNumber(str)) {
            return Double.parseDouble(str);
        } else {
            return 0d;
        }
    }

    @ActionMethod(name = "字符串的正则较验")
    @ActionMethodParameter(names = {"字符串", "正则表达式"})
    public boolean strMatches(String str, String pattern) {
        try {
            System.out.println("字符串" + str + " 正则表达式" + pattern);
            return Pattern.matches(pattern, str);
        } catch (Exception e) {
            return false;
        }
    }

    @ActionMethod(name = "字符串转换成数组")
    @ActionMethodParameter(names = {"字符串"})
    public String[] strToArray(String str) {
        return str.split("");
    }

    @ActionMethod(name = "字符串转换成集合")
    @ActionMethodParameter(names = {"字符串"})
    public List<String> strToList(String str) {
        return Arrays.asList(str.split(""));
    }


    @ActionMethod(name = "是否在时间区间内")
    @ActionMethodParameter(names = {"当前时间", "开始时间", "结束时间"})
    public Boolean isBetween(Date nowDate, String beginDate, String endDate) throws ParseException {
        Date begin = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDate);
        Date end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDate);
        long endTime = end.getTime();
        long beginTime = begin.getTime();
        long dateTime = nowDate.getTime();
        return dateTime > beginTime && dateTime < endTime;
    }

    /**
     * 计算输入区间日期的，命中夏季的天数，和非夏季天数，每年的7月1日-9月30日为夏季
     * @param startDate1 开始日期
     * @param endDate1 结束日期
     * @return [夏季天数，非夏季天数]
     */
    @ActionMethod(name = "求两个日期的夏季天数和非夏季天数")
    @ActionMethodParameter(names = {"开始日期","结束日期"})
    public List<Integer> getSummerDay(Date startDate1,Date endDate1)  {
        // 输入日期区间
        LocalDate startDate =startDate1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate endDate = endDate1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 调用方法计算夏季和非夏季天数
        int[] result = countSeasonDays(startDate, endDate);
        // 输出结果
       // System.out.println("夏季天数: " + result[0]);
       // System.out.println("非夏季天数: " + result[1]);

        List<Integer> list= new ArrayList<>();
        list.add(result[0]);
        list.add(result[1]);
        return  list;
    }

    public static int[] countSeasonDays(LocalDate startDate, LocalDate endDate) {
        int summerDays = 0;
        int nonSummerDays = 0;

        LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            if (currentDate.getMonthValue() >= 7 && currentDate.getMonthValue() <= 9) {
                summerDays++;
            } else {
                nonSummerDays++;
            }
            currentDate = currentDate.plusDays(1);
        }

        return new int[]{summerDays, nonSummerDays};
    }

    @ActionMethod(name = "根据对象创建新实例")
    @ActionMethodParameter(names = {"目标对象"}, enames = {"Object"})
    public Object newObjectInstanceByObject(Object paramObject) {
        try {
            if ((paramObject instanceof GeneralEntity)) {
                GeneralEntity localGeneralEntity = (GeneralEntity) paramObject;
                String str = localGeneralEntity.getTargetClass();
                GeneralEntity  newGeneralEntity = new GeneralEntity(str);
                WorkingMemory localWorkingMemory = WorkingMemoryHolder.getCurrentWorkingMemory();
                Utils.assignVariableObjectDefaultValue(newGeneralEntity, localWorkingMemory);
                if(!(paramObject ==null||localGeneralEntity.keySet().isEmpty())){
                    // 循环赋值吧
                    Iterator<String> iterator=localGeneralEntity.keySet().iterator();
                    while (iterator.hasNext()){
                        String key=iterator.next();
                        Object defaultValue=newGeneralEntity.get(key);
                        if(defaultValue==null){
                            newGeneralEntity.put(key,localGeneralEntity.get(key));
                            // 暂时不考虑更为复杂的数据类型了：若值为Object/List等，那就得向下递归...
                        }else {
                            // 使用默认值
                        }
                    }
                }
                return newGeneralEntity;
            }
            return paramObject.getClass().newInstance();
        } catch (Exception localException) {
            throw new RuleException(localException);
        }
    }


}
